package com.learn.algorithm_206;

import com.dataconsruct.ListNode;
import org.junit.Test;

/**
 * 反转链表
 * https://leetcode-cn.com/problems/reverse-linked-list/
 * @author gatts, 2022/1/12 18:45
 */
public class ReverseListNode {

    @Test
    public void test() {
        ListNode root1 = new ListNode(1);
        ListNode root2 = new ListNode(2);
        ListNode root3 = new ListNode(3);
        ListNode root4 = new ListNode(4);
        ListNode root5 = new ListNode(5);

        root1.next = root2;
        root2.next = root3;
        root3.next = root4;
        root4.next = root5;

        ListNode result = reverseList(root1);
        System.out.println(result.val);
    }

    public ListNode reverseList(ListNode head) {
        // 因为是单向链表，所以要提前保存前一个节点
        ListNode previous = null;
        ListNode current = head;

        while (current != null) {
            ListNode next = current.next;
            // 当前节点的下一个节点改为上一个节点
            current.next = previous;
            // 更新上一个节点为当前节点
            previous = current;
            // 继续找下一个节点
            current = next;
        }

        return previous;
    }

}
